package com.cmii.sjw.department.control.jsc.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.cmii.sjw.department.control.jsc.model.AiConfig;
import com.cmii.sjw.department.control.jsc.model.params.CqxczwyAiConfigParams;
import com.cmii.sjw.department.control.jsc.model.params.QAParams;
import com.cmii.sjw.department.control.jsc.service.AiService;
import com.cmii.sjw.department.control.jsc.service.BailianStreamAIService;
import com.cmii.sjw.department.control.jsc.util.AuthCodeTest;
import com.cmii.sjw.department.control.jsc.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import jakarta.annotation.Resource;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;

/**
 * AI接口
 * @Author jfh
 * @Date 2025-02-10 周一 10:17
 * @Version 1.0
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/ai")
public class AiController {

    @Resource
    private AiService aiService;

    @Autowired
    private BailianStreamAIService bailianStreamAIService;

    /**
     * 获取云从ai token
     * @return
     */
    @PostMapping("/getYcAiToken")
    public Result getYcAiToken() {
        return aiService.getYcAiToken();
    }

    /**
     * 获取云从ai答案详情
     * @param token 云从AI token
     * @param id 问答记录ID，id为智能体文本对话中的recordId
     * @return
     */
    @PostMapping("/detail")
    public Result detail(String token,String id) {
        return aiService.detail(token,id);
    }

    /**
     * 获取数字重庆人工智能底座配置
     * @return
     */
    @PostMapping("/cqxczwyAiConfig")
    public Result<AiConfig> cqxczwyAiConfig(@RequestBody CqxczwyAiConfigParams params) {
        log.info("数字重庆人工智能底座配置参数：{}",params);
        return aiService.cqxczwyAiConfig(params);
    }

    /**
     * 获取数字重庆人工智能底座问答
     * @param request 参数
     * @return 结果
     */
    @PostMapping(value = "/chat-messages", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chatMessages(@RequestBody QAParams request) {
        long startTime = System.currentTimeMillis();
        String sessionId = request.getSessionId();
        if (StringUtils.isEmpty(sessionId)) {
            //不能为空
            throw new IllegalArgumentException("sessionId不能为空");
        }

        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        // 异步处理流式请求
        CompletableFuture.runAsync(() -> {
            try {
                bailianStreamAIService.callStreamAgent(emitter, sessionId, request.getQuestion());
                // 记录成功耗时
                long endTime = System.currentTimeMillis();
                long duration = endTime - startTime;
                log.info("问答接口调用成功 - sessionId: {}, 耗时: {}ms", sessionId, duration);
            } catch (Exception e) {
                // 记录失败耗时
                long endTime = System.currentTimeMillis();
                long duration = endTime - startTime;
                log.error("问答接口调用失败 - sessionId: {}, 耗时: {}ms, 错误: {}", sessionId, duration, e.getMessage());
                try {
                    emitter.send(SseEmitter.event().name("error").data(e.getMessage()));
                    emitter.complete();
                } catch (IOException ioException) {
                    // 忽略
                }
            }
        });

        return emitter;
    }

    /**
     * 部门驾驶舱获取渝教通AI助手授权码
     * @return 授权码
     */
    @PostMapping("/deptToYjtAuthCode")
    public Result<String> deptToYjtAuthCode() {
        AuthCodeTest authCodeTest = new AuthCodeTest();
        try {
            String userId = StpUtil.getLoginIdAsString();
            String jsonData = String.format("{\"userId\":\"%s\",\"userType\":\"1\"}", userId);
            String authCode = authCodeTest.getAuthCode(jsonData);
            String encodedData = URLEncoder.encode(authCode, StandardCharsets.UTF_8);
            return Result.success(encodedData);
        } catch (NotLoginException e) {
            throw new RuntimeException("用户未登录", e);
        } catch (Exception e) {
            throw new RuntimeException("获取授权码失败", e);
        }
    }
}
